package com.xinxing.learning.security.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Base64;

@RestController
public class CaptchaController {

    private final DefaultKaptcha defaultKaptcha;

    public CaptchaController(DefaultKaptcha defaultKaptcha) {
        this.defaultKaptcha = defaultKaptcha;
    }

    @GetMapping(value = "/captcha")
    public String captcha(HttpServletRequest request) {
        //-------------------生成验证码 begin --------------------------
        //获取验证码文本内容
        String text = defaultKaptcha.createText();
        System.out.println("验证码内容：" + text);
        //将验证码文本内容放入session
        request.getSession().setAttribute("captcha", text);
        //根据文本验证码内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);

        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", fos);
            return Base64.getEncoder().encodeToString(fos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
